package cn.com.swu.mianyangapp.ui.news;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.android.material.tabs.TabLayout;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import cn.com.swu.mianyangapp.R;
import cn.com.swu.mianyangapp.ui.bean.News;
import cn.com.swu.mianyangapp.ui.bean.Remark;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NewsDetailActivity extends AppCompatActivity {
    private final String user = "likang";
    private final int userid = 1;

    final private String mIp = "192.168.58.15:8081";

    private TextView mTextViewTitle;
    private TextView mTextViewAuthor;
    private TextView mTextViewContext;
    private ImageView mImageView;
    private RecyclerView mRecyclerView;
    private Button mButton;
    private EditText mEditText;
    private NewsRemarkAdapter mNewsRemarkAdapter;

    private List<Remark> mRemarkList;
    private News mNews;
    private String Tag = "OKHttp_Activity";
    private Handler mHandler1;
    private Handler mHandler2;


    @Override
    @SuppressLint("HandlerLeak")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);Intent intent = getIntent();
        mNews = (News) intent.getSerializableExtra("News");

        supportActionBar.setTitle("新闻");
        initView();
        initEvent();
        if(mNews.getNews_allow() == 1){
            initDate();
            mHandler1 = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Log.e(Tag+"Remark", msg.toString());

                    mRemarkList = (List<Remark>) msg.obj;

                    mRecyclerView.getRecycledViewPool();
                    mRecyclerView.getRecycledViewPool().setMaxRecycledViews(0, 10);
                    mNewsRemarkAdapter = new NewsRemarkAdapter(NewsDetailActivity.this,mRemarkList);
                    mRecyclerView.setAdapter(mNewsRemarkAdapter);
                    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NewsDetailActivity.this);
                    mRecyclerView.setLayoutManager(layoutManager);
                }
            };
            mButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    OkHttpClient client = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().build();
                    Request request = new Request.Builder()
                            .url("http://" + mIp + "/remark_add/"+user+ "/"+userid + "/"+mNews.getNews_id()+"/"+mEditText.getText().toString())
                            .post(formBody)
                            .build();
                    Log.e(Tag,request.url().toString());
                    Call call = client.newCall(request);
                    try {
                        Response response = call.execute();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    Intent intent = getIntent();
                    finish();
                    startActivity(intent);

                }
            });
        }
        else {
            mButton.setVisibility(View.GONE);
            mEditText.setVisibility(View.GONE);
        }


    }

    @SuppressLint({"SetTextI18n", "HandlerLeak"})
    private void initEvent() {
        if(mNews != null){
            mTextViewContext.setText(mNews.getNews_context());
            mTextViewTitle.setText(mNews.getNews_name());
            mTextViewAuthor.setText(mNews.getNews_author() + " " + mNews.getNews_time());
            if (mNews.getNews_image_name() != null){
                getBitImage(mNews.getNews_image_name());
                mHandler2 = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (msg.what == 2){
                            Bitmap bitmap = (Bitmap) msg.obj;
                            mImageView.setImageBitmap(bitmap);
                        }
                    }
                };
            }
            else {
                mImageView.setVisibility(View.GONE);
            }
        }
    }

    private void getBitImage(String news_image_name) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://"+ mIp + "/"+news_image_name)
                .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                Log.e(Tag,e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream inputStream = response.body().byteStream();//得到图片的流
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                Message msg = new Message();
                msg.what = 2;
                msg.obj = bitmap;
                mHandler2.sendMessage(msg);

            }
        });
    }

    private void initDate() {

        OkHttpClient client = new OkHttpClient();
        FormBody body = new FormBody.Builder().build();
        Request request = new Request.Builder()
                .url("http://" + mIp + "/remark_query/"+mNews.getNews_id())
                .addHeader("Accept-Language","zh-CN,zh;q=0.9")
                .post(body)
                .build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String Tag = "OKHttp_Error";
                Log.e(Tag,e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                JSONArray jsonArray = JSON.parseArray(result);
                List<Remark> list = JSONObject.parseArray(jsonArray.toJSONString(), Remark.class);
                Message msg = Message.obtain();
                msg.obj = list; // 消息内存存放
                mHandler1.sendMessage(msg);
                Log.e(Tag + "_Data", result.toString());
            }
        });
    }

    private void initView(){
        mTextViewTitle = findViewById(R.id.news_detail_title);
        mTextViewAuthor = findViewById(R.id.news_detail_author);
        mTextViewContext = findViewById(R.id.news_detail_context);
        mImageView = findViewById(R.id.news_detail_image);
        mRecyclerView = findViewById(R.id.news_detail_remark);
        mButton = findViewById(R.id.Remark_sumbit);
        mEditText = findViewById(R.id.news_remark_input);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}